package cn.edu.nwsuaf.examcenter.service.serviceImpl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Hibernate;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import cn.edu.nwsuaf.examcenter.model.PageModel;
import cn.edu.nwsuaf.examcenter.pojo.Major;
import cn.edu.nwsuaf.examcenter.pojo.Sclass;
import cn.edu.nwsuaf.examcenter.service.BaseService;
import cn.edu.nwsuaf.examcenter.service.SclassService;

@Service(value="sclassService")
public class SclassServiceImpl extends BaseServiceImpl<Sclass> implements SclassService {

	@Override
	public void loadSclass(ModelMap modelMap) {
		// TODO Auto-generated method stub
		PageModel<Sclass> pageModel = new PageModel<>();
		List<Sclass> list = super.findAll(Sclass.class);
		pageModel.setTotalrows(list.size());
		pageModel.setList(list);
		modelMap.addAttribute("pageModel",pageModel);
	}

	@Override
	public void saveSclass(Sclass Sclass) {
		// TODO Auto-generated method stub
		super.saveData(Sclass);
	}

	@Override
	public void deleteSclass(String SclassNo) {
		// TODO Auto-generated method stub
		Sclass Sclass = super.getById(Sclass.class, SclassNo);
		super.deleteData(Sclass);
	}

	@Override
	public void deleteSclassList(String array) {
		// TODO Auto-generated method stub
		String[] SclassNos = array.split(",");
		List<Sclass> list = new ArrayList<>();
		for(String SclassNo : SclassNos){
			list.add(super.getById(Sclass.class, SclassNo));
		}
		super.deleteDataList(list);
	}

	@Override
	public List<Sclass> jsonLoadSclass(String gradeNo) {
		// TODO Auto-generated method stub
		String[] param = {gradeNo};
		return super.findAll("FROM Sclass as Sclass where Sclass.grade.gradeNo=?", param);
	}

	@Override
	public List<Sclass> jsonSearchSclass(String gradeNo, String sclassName) {
		// TODO Auto-generated method stub
		String hql = "FROM Sclass as sclass";
		List<String> keyList = new ArrayList<>();
		List<Sclass> list = new ArrayList<>();
		if(gradeNo!=null && sclassName!=null){
			keyList.add(gradeNo);
			keyList.add("%"+sclassName+"%");
			hql = hql+" where sclass.grade.gradeNo=? and sclass.className like(?)";
			
		}else if(gradeNo!=null && sclassName==null){
			keyList.add(gradeNo);
			hql = hql + " where sclass.grade.gradeNo=?";
		}else if(gradeNo==null && sclassName!=null){
			keyList.add("%"+sclassName+"%");
			hql = hql + " where sclass.className like(?)";
		}
		if(keyList.size()==0){
			list = super.findAll(Sclass.class);
		}else{
			String[] param = keyList.toArray(new String[keyList.size()]);
			list = super.findAll(hql, param);
		}
		for(Sclass sclass:list){//用于json数据的相关抓取
			Hibernate.initialize(sclass.getGrade());
			Hibernate.initialize(sclass.getGrade().getMajor());
			Hibernate.initialize(sclass.getGrade().getMajor().getCollege());
		}
		return list;
	}


}
